<template>
    <div>
      <div style="display:flex">
        <!-- <button class="" @click="draw()">绘制</button>
        <button class="" @click="disDraw()">关闭绘制</button>
        <button @click="create()">绘制矩形</button> -->
        <!-- <button @click="createIcon()">画icon</button>
        <button @click="createAnno()">画注记</button>
        <button @click="createPoint()">画点</button>
        <button @click="createLine()">画线</button>
        <button @click="createPolygon()">绘制多变形</button>
        <button @click="createpopup()">绘制弹出框</button> -->
        <button @click="addMarker()">画点</button>
        <button @click="createLine()">画线</button>
        <button @click="createFace()">画面</button>
        <button @click="removeMarkerLin()">移除点</button>
        <button @click="removeLine()">移除线</button>
        <button @click="removePolygon()">移除面</button>
      </div>
      <div id="map"></div>
    </div>
</template>

<script>
let map = null;
export default {
  data() {
    return {
      videoSearchID: 'require("./../../assets/avatar.png")',
      map: "",
      //  定义保存点位的数组变量
      pointMarkerList: [],
      //  定义保存线的相关变量
      markerList: [], // 绘制过程和最终存的点
      addLineArr: [], // 绘制过程中存取的线
      lineList: [], // 最终存的线的数
      //  定义保存面的相关变量
      points: [], // 画的过程中的点
      lines: {}, // 画的过程中生成的多边形
      tempLines: {}, // 鼠标移动中生成的多边形（实际是一条线段）
      polygonList: {}, // 双击结束生成多边形
      facelines: [], // 存储画的多边形
      facetempLines: [], // 存储移动的多边形
      facepolygonList: [] // 存储结束生成的多边形
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = L.map("map", {
        center: [19.15, 110.49], // 默认的地图中心点
        minZoom: 1, // 最小缩放级别
        maxZoom: 7, // 最大缩放级别
        zoom: 7, // 缩放比列
        zoomControl: false, // 禁用 + - 按钮
        doubleClickZoom: false, // 禁用双击放大
        attributionControl: false // 移除右下角leaflet标识
      });
      this.layerDom = L.tileLayer(
        "https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s,m&gl=CN&x={x}&y={y}&z={z}"
      ).addTo(this.map);
      //   this.map.removeLayer(this.layerDom)  // 移除地图图层
    },
    //  绘制点位
    addMarker() {
      // 资源下图
      this.removeMarkerLin();
      // 点击地图绘制点位
      this.map.once("click", e => {
        console.log(e);
        // 点位上图，数组保存
        this.pointMarkerList = [];
        const marker = L.marker([e.latlng.lat, e.latlng.lng], {
          id: this.videoSearchID
        }).addTo(this.map);
        this.pointMarkerList.push(marker);
        console.log(this.pointMarkerList);
      });
    },
    // 点位的删除
    removeMarkerLin() {
      this.pointMarkerList.forEach(item => {
        item.remove();
      });
      this.pointMarkerList = [];
    },
    //  面的绘制
    createFace() {
      this.removePolygon();
      // this.$message.success('请在地图绘制多边形,双击结束自动生成')
      this.lines = L.polyline([], {
        color: "#fc6a00",
        fillColor: "#fc6a00",
        fillOpacity: 0.2
      });
      this.tempLines = L.polyline([], {
        color: "#fc6a00",
        fillColor: "#fc6a00",
        fillOpacity: 0.2
      });
      this.map.addLayer(this.lines);
      this.map.addLayer(this.tempLines);

      this.map.on("click", e => {
        this.points.push([e.latlng.lat, e.latlng.lng]);
        this.lines.addLatLng(e.latlng);
        this.map.addLayer(this.lines);
        this.facelines.push(this.lines);
      });
      this.map.on("mousemove", e => {
        if (this.points.length > 0) {
          this.tempLines.setLatLngs([
            this.points[this.points.length - 1],
            [e.latlng.lat, e.latlng.lng]
          ]);
          this.map.addLayer(this.tempLines);
          this.facetempLines.push(this.tempLines);
        }
      });
      this.map.on("dblclick", e => {
        this.polygonList = L.polygon([this.points], {
          color: "#fc6a00",
          fillColor: "#fc6a00",
          fillOpacity: 0.2,
          id: this.videoSearchID
        }).addTo(this.map);
        this.map.addLayer(this.polygonList);
        this.facepolygonList.push(this.polygonList);
        this.points = [];
        this.lines.setLatLngs([]);

        this.map.off("click");
      });
    },
    // 面的删除
    removePolygon() {
      this.points.forEach(item => {
        this.map.removeLayer(item);
      });
      this.facelines.forEach(item => {
        this.map.removeLayer(item);
      });
      this.facetempLines.forEach(item => {
        this.map.removeLayer(item);
      });
      this.facepolygonList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.points = [];
      this.facelines = [];
      this.facetempLines = [];
      this.facepolygonList = [];
    },
    createAnno() {
      // 绘制注记
      let markerIcon = L.divIcon({
        html: "我是标注", //marker标注
        className: "my-div-icon",
        iconSize: [57, 71], //marker宽高
        iconAnchor: [28.5, 55], //文字标注相对位置
        iconColor: "pink"
      });
      var latlng = [40.35, 117.36];
      L.marker(latlng, { icon: markerIcon }).addTo(map);
      // 绑定点击事件获取属性信息
      // marker.on("click", e => {
      //   console.log("点击了");
      //   let data = e.target.options.data; //marker的属性信息
      // });

      return;
      // 1.添加注记
      // var markers=[[51.505,-0.09],[52,-1],[51,-0.05]]
      var markers = [[40.35, 117.36], [36.35, 114.36], [42.12, 113.933657]];
      for (i = 0; i < markers.length; i++) {
        L.marker(markers[i]).addTo(map);
      }
    },
    // 绘制单个icon
    createIcon() {
      L.marker([40.35, 117.36], {
        icon: new L.Icon({
          className: "lmap-icon",
          iconUrl: require("./../../assets/avatar.png"),
          iconSize: [24, 24],
          iconAnchor: [16, 16]
        })
      }).addTo(map);
    },
    createPoint() {
      // 绘制点
      L.circle([40.35, 117.36], {
        color: "#FF0000",
        fillColor: "#FF0000",
        radius: 1000,
        fillOpacity: 1
      }).addTo(map);
    },
    //  绘线
    createLine() {
      this.removeLine();
      // this.$message.success('请在地图上进行路线打点,双击结束打点')
      this.map.once("click", e => {
        this.addLineArr.push([e.latlng.lat, e.latlng.lng]);
        const marker = L.marker([e.latlng.lat, e.latlng.lng]).addTo(this.map);
        this.markerList.push(marker);
        this.map.on("click", e => {
          this.addLineArr.push([e.latlng.lat, e.latlng.lng]);
          // 绘点
          const marker = L.marker([e.latlng.lat, e.latlng.lng], {
            icon: this.mixMarkerPoint
          }).addTo(this.map);
          this.markerList.push(marker);
          // 绘线
          const line = L.polyline(this.addLineArr, {
            color: "#fc6a00",
            dashArray: "5,10"
          }).addTo(this.map);
          this.lineList.push(line);
        });
        this.map.once("dblclick", e => {
          this.addLineArr.push([e.latlng.lat, e.latlng.lng]);
          // 绘点
          const marker = L.marker([e.latlng.lat, e.latlng.lng], {
            icon: this.mixEndPoint
          }).addTo(this.map);
          this.markerList.push(marker);
          // 绘线
          const line = L.polyline(this.addLineArr, {
            color: "#fc6a00",
            dashArray: "5,10"
          }).addTo(this.map);
          this.lineList.push(line);

          // 结束绘制
          this.map.off("click");
        });
      });
    },
    // 线的删除
    removeLine() {
      this.markerList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.lineList.forEach(item => {
        this.map.removeLayer(item);
      });
      this.addLineArr = [];
      this.markerList = [];
      this.lineList = [];
    },

    // 绘制多边形
    createPolygon() {
      var latlngs = [[40.35, 117.36], [36.35, 114.36], [42.12, 113.933657]];
      var polygon = L.polygon(latlngs, {
        color: "#000eff",
        fillColor: "#0000ed",
        weight: 1
      }).addTo(map);
    },
    createpopup() {
      var popup = L.popup()
        .setLatLng([40.35, 117.36])
        .setContent("<p>你好呀！<br />我是个弹窗框.</p>")
        .openOn(map);
      // 或着对绘制好的图形绑定弹出框，在点击这个图形后会弹出你想要你内容
      polygon.bindPopup("我是个多边形");
    },
    draw() {
      this.map.pm.enableDraw("Polygon", {
        snappable: false
      });
      //   this.map.pm.enableDraw("Marker", { snappable: false });
      //   this.map.pm.enableDraw("CircleMarker", { snappable: false });
    },
    disDraw() {
      this.map.pm.disableDraw("Polygon");
      this.map.pm.disableDraw("Marker");
      this.map.pm.disableDraw("CircleMarker");
    },
    getlatLngs() {
      //pm:drawstart 开始第一个点的时候调用
      //pm:drawend  禁止绘制时调用
      //pm:create  创建完成时调用
      this.map.on("pm:drawstart", e => {
        console.log(e, "first");
      });
      this.map.on("pm:drawend", e => {
        console.log(e, "禁止绘制");
      });
      this.map.on("pm:create", e => {
        console.log(e, "绘制完成时调用");
        console.log(e.layer._latlngs[0], "绘制坐标");
      });
    },
    //  绘制
    drawPoint() {
      L.circle([51.3, -0.06], {
        color: "#FF0000",
        fillColor: "#FF0000",
        radius: 1000,
        fillOpacity: 1
      }).addTo(map);
    },
    drawLine() {
      var latlngs = [[51.505, -0.09], [52, -1], [51, -0.05]];
      var polyline = L.polyline(latlngs, { color: "red" }).addTo(map);
      var popup = L.popup()
        .setLatLng([51.505, -0.19])
        .setContent("<p>Hello world!<br />This is a nice popup.</p>")
        .openOn(map);

      polygon.bindPopup("我是个xian");
    },
    drawPolygon() {
      var latlngs = [[51.505, -0.09], [52, -1], [51, -0.05], [51.3, -0.06]];
      var polygon = L.polygon(latlngs, {
        color: "#000eff",
        fillColor: "#0000ed",
        weight: 1
      }).addTo(map);
      //  var popup = L.popup()
      //       .setLatLng([51.505, -0.19])
      //       .setContent('<p>Hello world!<br />This is a nice popup.</p>')
      //       .openOn(map);

      // polygon.bindPopup("我是个多边形")
    },
    // 进攻方向
    addAttackArrow() {
      L.Plot.attackArrow([
        [36.146608, 119.994049],
        [36.145499, 120.017395],
        [36.288425, 119.996796]
      ]).addTo(map);
    },
    // 画矩形
    create() {
      let list = [];
      let juxing;
      this.map.on("click", e => {
        list.push([e.latlng.lat, e.latlng.lng]);
        this.map.on("mousemove", ev => {
          if (list.length > 1) {
            list.splice(1);
          }
          list.push([ev.latlng.lat, ev.latlng.lng]);
          this.testgroup.clearLayers();
          juxing = L.rectangle(list, {
            //绘制矩形
            color: "#ff7800",
            weight: 1
          }).addTo(this.testgroup);
        });
        if (list.length > 1) {
          list.pop(); //第二次点击会触发第一次的push（）导致得到三个数据（后两个一样），所以删除最后一个
          // this.list.push([list])//保存矩形数据
          this.list.push({
            first: list[0],
            sec: list[1],
            name: "矩形" + (this.list.length + 1)
          }); //保存矩形数据
          this.map.off("mousemove"); //两点确定，移除鼠标移动事件
          this.map.off("click"); //两点确定，移除点击事件，
          this.testgroup.clearLayers();
          L.rectangle(list, {
            //绘制矩形
            color: "#ff7800",
            weight: 1
          }).addTo(this.rectgroup);
        }
      });
    },
    change(data) {
      this.markerlist = [];
      for (let key in data) {
        if (key !== "name") {
          let marker = "marker" + key;
          marker = L.marker(new L.LatLng(data[key][0], data[key][1]), {
            // 创建点
            icon: this.shipWreckIcon,
            draggable: true
          }).addTo(this.cirgroup);
          let _this = this;
          marker.on("drag", function(e) {
            data[key] = [e.latlng.lat, e.latlng.lng];
            _this.drawrect(_this.rectgroup, [data]);
          });
          this.markerlist.push(marker);
        }
      }
    },
    drawrect(group, data, clear = true) {
      data.forEach((items, index) => {
        let list = [items.first, items.sec];
        if (clear) {
          group.clearLayers(); //清除当前绘制的图层，保留了原有图层，需要删除可以添加
        }
        L.rectangle(list, {
          //绘制矩形
          color: "#ff7800",
          weight: 1
        }).addTo(group);
      });
    },
    sub() {
      this.markerlist.forEach(item => {
        item.off("drag");
      });
      this.cirgroup.clearLayers();
      this.testgroup.clearLayers();
      this.rectgroup.clearLayers();
      this.drawrect(this.rectgroup, this.list, false);
    }
  }
};
</script>

<style scoped>
#map {
  width: 100%;
  height: calc(100vh);
  z-index: 1;
}
.draw {
  display: flex;
  z-index: 2;
  width: 100px;
  height: 50px;
  position: absolute;
  left: 50px;
  justify-content: center;
  align-items: center;
}

.disDraw {
  display: flex;
  z-index: 2;
  width: 100px;
  height: 50px;
  position: absolute;
  left: 200px;
  justify-content: center;
  align-items: center;
}
</style>
